using System;
using System.Collections.Generic;
using System.Reflection;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace Report
{
	public class WordOperator
	{
		public static bool ExportToPDF(string wordFile, string xpsFile)
		{
			return ExportToFile(wordFile, xpsFile, WdSaveFormat.wdFormatPDF);
		}

		public static bool ExportToXPS(string wordFile, string xpsFile)
		{
			return ExportToFile(wordFile, xpsFile, WdSaveFormat.wdFormatXPS);
		}

		private static bool ExportToFile(string wordFile, string xpsFile, WdSaveFormat format)
		{
			bool result = false;
			object obj = null;
			Type type = null;
			try
			{
				type = Type.GetTypeFromProgID("Word.Application");
				if (type == null)
				{
					Log.WriteLine("没有安装Word。");
					return false;
				}
				obj = Activator.CreateInstance(type);
				object obj2 = obj.GetType().InvokeMember("Documents", BindingFlags.GetProperty, Type.DefaultBinder, obj, null);
				object target = obj2.GetType().InvokeMember("Open", BindingFlags.InvokeMethod, null, obj2, new object[3] { wordFile, true, true });
				obj2.GetType().InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, target, new object[2] { xpsFile, format });
				obj2.GetType().InvokeMember("Close", BindingFlags.InvokeMethod, null, target, new object[1] { WdSaveOptions.wdDoNotSaveChanges });
				result = true;
			}
			catch (Exception ex)
			{
				Log.WriteLine(ex.StackTrace);
			}
			finally
			{
				if (type != null && obj != null)
				{
					type.InvokeMember("Quit", BindingFlags.InvokeMethod, null, obj, new object[1] { WdSaveOptions.wdDoNotSaveChanges });
				}
			}
			return result;
		}

		public static int CreateDocxFile(string fileName)
		{
			WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document);
			MainDocumentPart mainDocumentPart = wordprocessingDocument.AddMainDocumentPart();
			mainDocumentPart.Document = new Document(new Body());
			mainDocumentPart.Document.Save();
			wordprocessingDocument.Close();
			return 0;
		}

		public static void EnumerateTextAndDrawing(IEnumerable<OpenXmlElement> list, List<Text> textList, List<Drawing> drawingList)
		{
			foreach (OpenXmlElement item in list)
			{
				if (item is Text && !string.IsNullOrEmpty(((Text)item).Text))
				{
					textList.Add((Text)item);
				}
				if (item is Drawing)
				{
					drawingList.Add((Drawing)item);
				}
				else
				{
					EnumerateTextAndDrawing(item.ChildElements, textList, drawingList);
				}
			}
		}

		public static void EnumerateTable(IEnumerable<OpenXmlElement> list, List<Table> tableList)
		{
			foreach (OpenXmlElement item in list)
			{
				if (item is Table)
				{
					tableList.Add((Table)item);
				}
				else
				{
					EnumerateTable(item.ChildElements, tableList);
				}
			}
		}
	}
}
